<template>
  <!-- 抽奖城市管理Dialog -->
  <el-dialog v-model="dialogFormVisible" :title="title" width="600px" @close="close">
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <!-- 车辆名称 -->
      <el-form-item label="车辆名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入车辆名称" />
      </el-form-item>

      <!-- 排序 -->
      <el-form-item label="排序" prop="sort">
        <el-input v-model="form.sort" placeholder="请输入排序" type="number" />
      </el-form-item>

      <!-- 图片 -->
      <el-form-item label="图片" prop="image">
        <QsUpload v-model="form.image" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { addApi, updateApi } from '/@/api/my'
import QsUpload from '/@/components/QsUpload/image.vue'

const emit = defineEmits(['fetch-data'])
const $baseMessage = inject<any>('$baseMessage')

const form = ref<any>({})
const rules = ref<any>({
  name: [{ required: true, trigger: 'blur', message: '请输入车辆名称' }],
})
const title = ref<string>('')
const dialogFormVisible = ref<boolean>(false)
const formRef = ref()

onMounted(() => {})

const showEdit = (row: any) => {
  if (!row) {
    title.value = '添加'
    form.value = reactive({
      name: '',
      sort: '',
      image: '',
    })
  } else {
    title.value = '编辑'
    form.value = reactive({
      ...row,
      image: row.image || '',
    })
  }

  dialogFormVisible.value = true
}
const close = () => {
  formRef.value.resetFields()
  dialogFormVisible.value = false
}
const save = async () => {
  await formRef.value?.validate().then(async () => {
    if (title.value == '添加') {
      await addApi(form.value)
      $baseMessage('添加成功！', 'success', 'vab-hey-message-success')
      emit('fetch-data')
      close()
    } else {
      await updateApi(form.value)
      $baseMessage('修改成功！', 'success', 'vab-hey-message-success')
      emit('fetch-data')
      close()
    }
  })
}

defineExpose({
  showEdit,
})
</script>

<style lang="scss" scoped></style>
